/**
 * @title ScoreActivity.java
 * @package com.esun.cheetah.view.match.matchlist
 * @description 比分Activity
 * @author liugan
 * @date 2012-7-23
 * @copyright 深圳市易讯天空
 */
package com.esun.cheetah.view.match.matchlist;

import java.lang.reflect.Field;
import java.util.ArrayList;

import com.esun.cheetah.R;
import com.esun.cheetah.biz.match.matchlist.MatchListManager;
import com.esun.cheetah.biz.match.matchlist.MatchListScoreCommunicater;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.config.Language;
import com.esun.cheetah.model.match.matchlist.Match;
import com.esun.cheetah.view.match.matchlist.fragments.AbsListFragment;
import com.esun.cheetah.view.match.matchlist.fragments.AllMatchFragment;
import com.esun.cheetah.view.match.matchlist.fragments.AttentionMatchFragment;
import com.esun.cheetah.view.match.matchlist.fragments.OverMatchFragment;
import com.esun.cheetah.view.match.matchlist.fragments.PlayingMatchFragment;
import com.esun.cheetah.view.match.matchlist.fragments.RecommendMatchFragment;
import com.esun.cheetah.view.match.matchlist.fragments.UnplayedMatchFragment;
import com.esun.util.log.EDebug;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @title ScoreActivity
 * @description 比分Activity
 * @author liugan
 */
public class ScoreActivity extends FragmentActivity{
	
	
	public static final int UPDATE_SUCCESS = 0;
	
	public final String[] TAB_TITLES = {
			"推荐",
			"所有",
			"进行中",
			"未开赛",
			"已结束",
			"关注",
	};
	
	
	private TabHost mTabHost;
    private ViewPager  mViewPager;
    private TabsAdapter mTabsAdapter;
    private LayoutInflater inflater;
	private TextView tvRecommendCount,tvAllCount,tvPlayingCount,tvUnplayedCount,tvOverCount,tvAttentionedCount,tvAttentionedPlayingCount;	
	private ProgressBar mProgress;
	
	/**
	 * 标识当前是否正在刷新
	 */
	private boolean isUpdating;
	
	private MatchListManager mMatchListManager = MatchListManager.getInstance();
	private MatchListScoreCommunicater mCommunicater;
	private Handler mUpdateHandler = new UpdateHandler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.score_activity);
        tvAttentionedPlayingCount = (TextView)findViewById(R.id.tv_attentioned_playing_match_count);
        mProgress = (ProgressBar)findViewById(R.id.pb_loading_matches);
        
        mTabHost = (TabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup();

        inflater = LayoutInflater.from(this);

        mViewPager = (ViewPager)findViewById(R.id.matches_pager);
        mViewPager.setPageMargin(20);
        //修改ViewPager切换View的动画
        try {
            Field mScroller;
            mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true); 
            Interpolator sInterpolator = new DecelerateInterpolator();
            FixedSpeedScroller scroller = new FixedSpeedScroller(mViewPager.getContext(),sInterpolator);
            mScroller.set(mViewPager, scroller);
        } catch (NoSuchFieldException e) {
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        }
        
        mViewPager.setOffscreenPageLimit(6);
        mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);

        //推荐比赛的Fragment
        mTabsAdapter.addTab(mTabHost.newTabSpec(TAB_TITLES[0]).setIndicator(getIndicator(TAB_TITLES[0])),
        		RecommendMatchFragment.class, null);
        //所有比赛的Fragment
        mTabsAdapter.addTab(mTabHost.newTabSpec(TAB_TITLES[1]).setIndicator(getIndicator(TAB_TITLES[1])),
        		AllMatchFragment.class, null);
        //进行中比赛的Fragment
        mTabsAdapter.addTab(mTabHost.newTabSpec(TAB_TITLES[2]).setIndicator(getIndicator(TAB_TITLES[2])),
        		PlayingMatchFragment.class, null);
        //未开赛比赛的Fragment
        mTabsAdapter.addTab(mTabHost.newTabSpec(TAB_TITLES[3]).setIndicator(getIndicator(TAB_TITLES[3])),
        		UnplayedMatchFragment.class, null);
        //已结束比赛的Fragment
        mTabsAdapter.addTab(mTabHost.newTabSpec(TAB_TITLES[4]).setIndicator(getIndicator(TAB_TITLES[4])),
        		OverMatchFragment.class, null);
        //关注比赛的Fragment
        mTabsAdapter.addTab(mTabHost.newTabSpec(TAB_TITLES[5]).setIndicator(getIndicator(TAB_TITLES[5])),
        		AttentionMatchFragment.class, null);
        
        //还原到保存的页面
        if (savedInstanceState != null) {
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
        }
                
        asynchronizeUpdate();
        
    }

    
    /**
     * @title setMatchesCount
     * @description 设置标签页上面的比赛场数
     */
    public void updateMatchesCount(){
    	final int currentTab = mTabHost.getCurrentTab();
    	if(currentTab == 0){
        	tvRecommendCount.setText(String.valueOf(mMatchListManager.getRecommendCount()));
    	}else{
        	tvRecommendCount.setText("("+String.valueOf(mMatchListManager.getRecommendCount())+")");
    	}
    	
    	if(currentTab == 1){
        	tvAllCount.setText(String.valueOf(mMatchListManager.getPlayingCount()+mMatchListManager.getUnplayedCount()+mMatchListManager.getOverCount()));
    	}else{
        	tvAllCount.setText("("+String.valueOf(mMatchListManager.getPlayingCount()+mMatchListManager.getUnplayedCount()+mMatchListManager.getOverCount())+")");
    	}
    	
    	if(currentTab == 2){
        	tvPlayingCount.setText(String.valueOf(mMatchListManager.getPlayingCount()));
    	}else{
        	tvPlayingCount.setText("("+String.valueOf(mMatchListManager.getPlayingCount())+")");
    	}
    	
    	if(currentTab == 3){
    		tvUnplayedCount.setText(String.valueOf(mMatchListManager.getUnplayedCount()));
    	}else{
    		tvUnplayedCount.setText("("+String.valueOf(mMatchListManager.getUnplayedCount())+")");
    	}
    	
    	if(currentTab == 4){
    		tvOverCount.setText(String.valueOf(mMatchListManager.getOverCount()));
    	}else{
    		tvOverCount.setText("("+String.valueOf(mMatchListManager.getOverCount())+")");
    	}
    	
    	if(currentTab == 5){
    		tvAttentionedCount.setText(String.valueOf(mMatchListManager.getAttentionedCount()));
    	}else{
    		tvAttentionedCount.setText("("+String.valueOf(mMatchListManager.getAttentionedCount())+")");
    	}
    	
    	tvAttentionedPlayingCount.setText(String.valueOf(mMatchListManager.getAttentionedPlayingCount()));
    }
    
    /**
	 * @title getIndicator
	 * @description 生成各个tabwidget的View
	 * @param string
	 * @return
	 */
	private View getIndicator(String title) {
		View view = (View) inflater.inflate(R.layout.tab_indicator_item_layout, null);
		TextView tvTitle = (TextView) view.findViewById(R.id.tv_indicator);
		tvTitle.setText(title);
		TextView tvCount = (TextView)view.findViewById(R.id.tv_indicator_matches_count);
		if(TAB_TITLES[0].equals(title)){
			tvRecommendCount = tvCount;
			view.setTag(tvRecommendCount);
		}else if(TAB_TITLES[1].equals(title)){
			tvAllCount = tvCount;
			view.setTag(tvAllCount);
		}else if(TAB_TITLES[2].equals(title)){
			tvPlayingCount = tvCount;
			view.setTag(tvPlayingCount);
		}else if(TAB_TITLES[3].equals(title)){
			tvUnplayedCount = tvCount;
			view.setTag(tvUnplayedCount);
		}else if(TAB_TITLES[4].equals(title)){
			tvOverCount = tvCount;
			view.setTag(tvOverCount);
		}else if(TAB_TITLES[5].equals(title)){
			tvAttentionedCount = tvCount;
			view.setTag(tvAttentionedCount);
		}
		return view;
	}
	

	@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("tab", mTabHost.getCurrentTabTag());
    }

	/**
	 * @title asynchronizeUpdate
	 * @description 异步刷新
	 */
	public void asynchronizeUpdate(){
		if(!isUpdating){
			isUpdating = true;
			mProgress.setVisibility(View.VISIBLE);
			mCommunicater = new MatchListScoreCommunicater(mUpdateHandler , null, 0);
			mCommunicater.startCommunicate();
		}
	}


	/**
	 * @title updateSuccess
	 * @description 刷新成功后的操作 
	 */
	private void updateSuccess(){
		mProgress.setVisibility(View.INVISIBLE);
		updateMatchesCount();
		updateMatchesList();
		isUpdating = false;
	}
	
	
	private void updateFailed(){
		mProgress.setVisibility(View.INVISIBLE);
		isUpdating = false;
		Toast.makeText(this, Language.INTERNET_FAIL, Toast.LENGTH_SHORT).show();
	}
	
	public void updateMatchesList(){
		for(int i=0; i<6; i++){
			AbsListFragment fragment = (AbsListFragment)this.getSupportFragmentManager().findFragmentByTag(getFragmentTag(i));
			if(fragment != null){
				fragment.update();
			}
		}
	}
	
	private String getFragmentTag(int pos){
	    return "android:switcher:"+R.id.matches_pager+":"+pos;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Activity parent = getParent();
			if (parent != null) {
				parent.onKeyDown(keyCode, event);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	
	/**
     * This is a helper class that implements the management of tabs and all
     * details of connecting a ViewPager with associated TabHost.  It relies on a
     * trick.  Normally a tab host has a simple API for supplying a View or
     * Intent that each tab will show.  This is not sufficient for switching
     * between pages.  So instead we make the content part of the tab host
     * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
     * view to show as the tab content.  It listens to changes in tabs, and takes
     * care of switch to the correct paged in the ViewPager whenever the selected
     * tab changes.
     */
    public class TabsAdapter extends FragmentPagerAdapter
            implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
        private final Context mContext;
        private final TabHost mTabHost;
        private final ViewPager mViewPager;
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
        private int lastTab = -1;

        final class TabInfo {
            private final Class<?> clss;
            private final Bundle args;

            TabInfo(String _tag, Class<?> _class, Bundle _args) {
                clss = _class;
                args = _args;
            }
        }

        /**
         * @title DummyTabFactory
         * @description 实现一个哑的TabContentFactory，真正的TabContent由ViewPager提供
         * @author liugan
         */
        class DummyTabFactory implements TabHost.TabContentFactory {
            private final Context mContext;

            public DummyTabFactory(Context context) {
                mContext = context;
            }

            @Override
            public View createTabContent(String tag) {
                View v = new View(mContext);
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }
        }

        public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
            mTabHost = tabHost;
            mViewPager = pager;
            mTabHost.setOnTabChangedListener(this);
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
            mTabHost.getTabWidget().setDividerDrawable(R.drawable.imh_default_halvingline);
        }

        public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
            tabSpec.setContent(new DummyTabFactory(mContext));
            String tag = tabSpec.getTag();

            TabInfo info = new TabInfo(tag, clss, args);
            mTabs.add(info);
            mTabHost.addTab(tabSpec);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.clss.getName(), info.args);
        }

        
        @Override
        public void onTabChanged(String tabId) {
        	
        	//找到当前Tab的索引
        	int position = mTabHost.getCurrentTab();
        	if( position >= 0 && position < TAB_TITLES.length){
        		View childTab = mTabHost.getTabWidget().getChildTabViewAt(position);
        		//将当前选中的Tab效果设置好
        		if(childTab != null){
        			if(position == 0){
        				childTab.setBackgroundResource(R.drawable.tab_foused_left);
        			}else if(position == TAB_TITLES.length-1){
        				childTab.setBackgroundResource(R.drawable.tab_foused_right);
        			}else{
        				childTab.setBackgroundResource(R.drawable.tab_foused_middle);
        			}
        			
        			TextView tvCount = (TextView)childTab.getTag();
        			if(tvCount != null){
						String count = tvCount.getText().toString();
						count = count.replace("(", "");
						count = count.replace(")","");
						tvCount.setBackgroundResource(R.drawable.bg_default_tabnumber);
						
						tvCount.setText(count);
        			}
        		}
 	
	        	//将之前的Tab效果清除
	        	if(lastTab != -1){
	        		View lastChildTab = mTabHost.getTabWidget().getChildTabViewAt(lastTab);
	        		if(lastChildTab != null){
	        			
	        			lastChildTab.setBackgroundColor(android.R.color.transparent);
	        			TextView tvCount = (TextView)lastChildTab.getTag();
	        			if(tvCount != null){
							String count = tvCount.getText().toString();
							tvCount.setBackgroundColor(android.R.color.transparent);
							
							tvCount.setText("("+count+")");
	        			}
	        		}
	        	}
	        	
	        	//更新最近的Tab为当前Tab
	        	lastTab = position;
        	
            mViewPager.setCurrentItem(position);
        	}
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            // Unfortunately when TabHost changes the current tab, it kindly
            // also takes care of putting focus on it when not in touch mode.
            // The jerk.
            // This hack tries to prevent this from pulling focus out of our
            // ViewPager.
        	//处理tabwidget中的焦点
           // TabWidget widget = mTabHost.getTabWidget();
           // int oldFocusability = widget.getDescendantFocusability();
            //widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
            mTabHost.setCurrentTab(position);
            
            AbsListFragment fragment = (AbsListFragment)ScoreActivity.this.getSupportFragmentManager().findFragmentByTag(getFragmentTag(position));
    		
    		fragment.checkUpdate();
            
            //widget.setDescendantFocusability(oldFocusability);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        	
        }
    }
	
   
    
	/**
	 * @title ScoreHandler
	 * @description 获取比分列表时用此Handler
	 * @author liugan
	 */
	class UpdateHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			EDebug.o("AbsListFragment","handlerMessage");
				switch (msg.what) {
				case Config.COMMUNICATER_SUCCESS:
					EDebug.o("AbsListFragment","COMMUNICATER_SUCCESS");
					
					ArrayList<Match> list = mCommunicater.getMatchList();
					mMatchListManager.updateMatches(list);
					updateSuccess();

					break;
				case Config.COMMUNICATER_FAIL:
					updateFailed();
					break;
					
				case Config.COMMUNICATER_EXCEPTION:
					updateFailed();
					break;
					
				default:
					updateFailed();
					break;
					
				}
		}
	}
    
}
